<template>
  <div class="account">
    <div class="config-wrapper">
      <div class="section-header">
        <h3>配置信息</h3>
      </div>

      <van-form ref="cardKeyFormRef">
        <van-cell-group inset>
          <van-field v-model="cardKeyConfig.oldCardKey" name="oldCardKey" clearable placeholder="请输入旧卡密"
            :rules="[{ required: true, message: '请输入旧卡密' }]">
            <template #label>
              <van-icon name="shield-o" style="margin-right: 5px" />旧卡密
            </template>
            <template #button>
              <div style="display: flex; align-items: center;">
                <van-button type="primary" size="small" block @click="handleSysConfigSubmit">同步卡密</van-button>
              </div>
            </template>
          </van-field>
        </van-cell-group>
      </van-form>
    </div>

    <van-form :key="formKey" ref="formRef">
      <van-cell-group inset>
        <van-field disabled v-model="mainAccount.expirationTime" name="expirationTime" placeholder="请输入到期时间"
          :rules="[{ required: true, message: '请输入到期时间' }]">
          <template #label>
            <van-icon name="clock-o" style="margin-right: 5px" />到期时间
          </template>
        </van-field>

        <van-field v-model="mainAccount.phoneNumber" name="phoneNumber"
          :rules="[{ required: true, message: '请输入手机号' }, { validator: validatePhoneNumber, message: '请输入正确的手机号' }]"
          clearable placeholder="请输入手机号">
          <template #label>
            <van-icon name="phone-o" style="margin-right: 5px" />手机号
          </template>
          <template #button>
            <div style="display: flex; align-items: center;">
              <van-button size="small" type="primary" :disabled="isCounting" @click="sendVerificationCode">
                {{ !isCounting ? buttonText : countdown + 's 后重新发送' }}
              </van-button>
            </div>
          </template>
        </van-field>

        <van-field v-model="mainAccount.code" name="code" :rules="[{ required: true, message: '请输入短信验证码' }]" clearable
          placeholder="请输入短信验证码" border="{{ false }}">
          <template #label>
            <van-icon name="shield-o" style="margin-right: 5px" />验证码
          </template>
          <template #button>
            <div style="display: flex; align-items: center;">
              <van-button size="small" type="primary" @click="getTokenCode">
                获取 Token
              </van-button>
            </div>
          </template>
        </van-field>

        <van-field class="form-textarea" v-model="mainAccount.allStr" rows="5" name="token" label-align="top"
          type="textarea"
          :rules="[{ required: true, message: '请输入接单Token' }, { validator: validateToken, message: '请输入正确的格式' }]"
          placeholder="请输入接单Token">
        </van-field>

        <van-field name="btn">
          <template #input>
            <van-button @click="submitMainAccountInfo" type="primary" size="small" block native-type="submit"
              class="submit-btn">
              同步主号
            </van-button>
            <div style="width: 10px;"></div>
            <van-button @click="getToken" type="primary" size="small" block native-type="submit" class="submit-btn">
              同步小号
            </van-button>
          </template>
        </van-field>

      </van-cell-group>
    </van-form>

    <div class="main-account-section">
      <div class="section-header">
        <h3>主号信息</h3>
      </div>

      <van-form class="main-account-form black-color">
        <van-field disabled name="phoneNumber" clearable placeholder="请输入手机号">
          <template #label>
            <van-icon name="phone-o" style="margin-right: 5px" />手机号
          </template>
          <template #input>
            <span style="color: #666;">{{ mainInfo.phoneNumber || '--' }}</span>
          </template>
        </van-field>

        <van-field disabled label="cid" name="cid" placeholder="请输入接单Token">
          <template #label>
            <van-icon name="link-o" style="margin-right: 5px" />cid
          </template>
          <template #input>
            <span style="color: #666;">{{ mainInfo.cid || '--' }}</span>
          </template>
        </van-field>

        <van-field disabled label="token" rows="5" name="token" type="textarea" placeholder="请输入接单Token">
          <template #label>
            <van-icon name="link-o" style="margin-right: 5px" />Token
          </template>
          <template #input>
            <div class="token-content" style="border: 0; padding: 5px 0;">
              {{ mainInfo.token || '暂无Token' }}
            </div>
          </template>
        </van-field>
      </van-form>
    </div>

    <div class="sub-accounts-section">
      <div class="section-header">
        <h3>小号信息</h3>
      </div>
      <div v-for="(account, index) in additionalAccounts" :key="index" class="additional-account">
        <van-cell-group inset>
          <van-field name="btn" class="account-title">
            <template #input>
              小号[{{ account.phone.slice(-4) }}]
            </template>
          </van-field>

          <van-field disabled v-model="account.token" name="token" label-align="top" placeholder="请先获取接单Token"
            class="token-display">
            <template #input>
              <div class="token-content">
                {{ account.phone + '|' + '|' + account.cid + '|' + account.token || '暂无Token' }}
              </div>
            </template>
          </van-field>

          <van-field name="btn">
            <template #input>
              <van-button type="danger" size="small" block class="submit-btn" @click="removeAccount(index)">
                删除小号
              </van-button>
            </template>
          </van-field>
        </van-cell-group>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useStore } from 'vuex';
import { showNotify } from 'vant';
import { StorageUtil } from '@/utils/storage'
import { loginApi, subTokenApi } from '@/api'
import qs from 'qs'


export default {
  setup() {
    // 卡密配置
    const cardKeyFormRef = ref(null);
    const cardKeyConfig = reactive({
      oldCardKey: '',
    });

    const handleSysConfigSubmit = () => {
      const newCardKey = StorageUtil.getCardKey();
      cardKeyFormRef.value.validate().then(() => {
        // 调用卡密同步的 API
        subTokenApi.sysConfig({
          oldCardKey: cardKeyConfig.oldCardKey,
          newCardKey: newCardKey
        }).then(res => {
          // 更新配置
          getUserInfo()
          showNotify({ type: 'success', message: '卡密同步成功' });
        }).catch(error => {
          console.error('卡密同步错误:', error);
          showNotify({ type: 'danger', message: error.retMsg || '卡密同步出现错误' });
        });
      }).catch(error => {
        console.warn('卡密同步表单验证错误:', error);
      })
    };



    const formRef = ref(null);
    const formKey = ref(0)
    const store = useStore();
    const active = computed(() => store.state.active)

    watch(active, (newValue) => {
      if (newValue === '1') {
        getUserInfo()
      }
    })

    // 账号表单
    const mainAccount = reactive({
      phoneNumber: '',
      expirationTime: '',
      allStr: '',
      token: '',
      code: '',
      cid: ''
    });

    // 获取主号信息
    const mainInfo = reactive({
      phoneNumber: '',
      expirationTime: '',
      token: '',
      cid: ''
    });

    const isCounting = ref(false);
    const buttonText = ref('发送验证码');
    const countdown = ref(60);

    const sendVerificationCode = () => {
      formRef.value.validate('phoneNumber').then(() => {
        // 调用发送验证码的 API
        subTokenApi.getMessageAuthenticationCode(mainAccount.phoneNumber).then((res) => {
          showNotify({ type: 'success', message: res });
          // 开始倒计时
          isCounting.value = true;
          buttonText.value = `发送验证码`;

          const timer = setInterval(() => {
            countdown.value--;

            if (countdown.value <= 0) {
              clearInterval(timer);
              isCounting.value = false;
              buttonText.value = '发送验证码';
              countdown.value = 60;
            }
          }, 1000);
        }).catch(error => {
          showNotify({ type: 'danger', message: error });
          console.error('发送验证码错误:', error);
        });
      }).catch(error => {
        console.warn('表单验证错误:', error);
      });
    };

    // 额外账号状态
    const additionalAccounts = ref([]);
    const newAccountPhone = ref('');
    const newAccountCode = ref('');

    // 验证手机号码
    const validatePhoneNumber = (phoneNumber) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phoneNumber);
    };

    const validateToken = (value) => {
      const tokenRegex = /^1[3-9]\d{9}\|.*\|.*$/;
      return tokenRegex.test(value);
    };

    // 提交主账号信息
    const submitMainAccountInfo = () => {
      formRef.value.validate(['token']).then(() => {
        // 为了清空无用的校验报错
        formKey.value++
        // 调用获取Token的API
        saveConfig()
      }).catch(error => {
        console.error('表单验证错误:', error);
      });
    };

    // 获取 Token
    const getTokenCode = () => {
      formRef.value.validate('code').then(() => {
        subTokenApi.getTokenBySMSCode(mainAccount.phoneNumber, mainAccount.code).then((retData) => {
          if (retData.access_token) {
            // 更新主账号tk
            mainAccount.token = retData.access_token
            mainAccount.cid = retData.cid
            mainAccount.allStr = (mainAccount.phoneNumber && mainAccount.token && mainAccount.cid) ? mainAccount.phoneNumber + '|' + retData.cid + '|' + retData.access_token : ''
            showNotify({ type: 'success', message: '获取Token成功!' });
          } else {
            // 如果没有显示错误原因
            const data = JSON.parse(retData.data)

            return Promise.reject(data)
          }
        }).catch(error => {
          showNotify({ type: 'danger', message: error.message || '配置保存失败' });
        });
      }).catch(error => {
        console.warn('表单验证错误:', error);
      })
    }

    // 监听 mainAccount.allStr
    watch(() => mainAccount.allStr, (newValue) => {
      if (newValue) {
        const parts = newValue.split('|');
        mainAccount.phoneNumber = parts[0] || '';
        mainAccount.token = parts[2] || '';
        mainAccount.cid = parts[1] || '';
        console.log(mainAccount);
      }
    })

    // 保存配置
    const saveConfig = () => {
      // 获取卡密
      const cardKey = StorageUtil.getCardKey();

      loginApi.login(cardKey)
        .then(response => {
          console.log('mainAccount.token', mainAccount.token);
          // 使用解构赋值，确保不会意外覆盖其他属性
          response.phoneNumber = mainAccount.phoneNumber
          response.token = mainAccount.token
          response.cid = mainAccount.cid
          // 主号信息更新
          mainInfo.phoneNumber = response.phoneNumber || '';
          mainInfo.token = response.token || '';
          mainInfo.cid = response.cid || '';
          // 调用API提交
          loginApi.updateUserConfig(response)
            .then(response => {
              // 保存主账号信息
              StorageUtil.setToken(mainAccount.token)
              StorageUtil.setUserInfo(response)
              showNotify({ type: 'success', message: '配置保存成功' });
            })
            .catch(error => {
              showNotify({ type: 'danger', message: error.message || '配置保存失败' });
            });
        })
        .catch(error => {
          console.error(error);
          showNotify({ type: 'danger', message: '获取加载失败！' });
        });
    };

    // 添加新账号
    const addAccount = () => {
      // 更新主账号tk
      additionalAccounts.value.unshift({
        phone: mainAccount.phoneNumber,
        token: mainAccount.token,
        cid: mainAccount.cid
      });

      // 获取卡密
      const cardKey = StorageUtil.getCardKey();

      // 准备保存的小号数据
      const subTokens = JSON.stringify(additionalAccounts.value);

      const param = qs.stringify({ cardKey, subTokens })

      // 调用保存小号接口
      subTokenApi.saveSubTokens(param)
        .then(() => {
          // 重置表单
          newAccountPhone.value = '';
          showNotify({ type: 'success', message: '小号更新成功!' });
        })
        .catch(error => {
          // 如果保存失败，移除刚添加的账号
          additionalAccounts.value.shift();
          showNotify({ type: 'danger', message: '小号更新失败：' + error.message });
        });
    };

    // 删除账号
    const removeAccount = (index) => {
      const removedAccount = additionalAccounts.value.splice(index, 1)[0];

      // 获取卡密
      const cardKey = StorageUtil.getCardKey();

      // 准备保存的小号数据
      const subTokens = JSON.stringify(additionalAccounts.value);

      const param = qs.stringify({ cardKey, subTokens })

      // 调用保存小号接口
      subTokenApi.saveSubTokens(param)
        .then(() => {
          showNotify({ type: 'success', message: '小号删除成功' });
        })
        .catch(error => {
          // 如果删除失败，恢复删除的账号
          additionalAccounts.value.splice(index, 0, removedAccount);
          showNotify({ type: 'danger', message: '小号删除失败：' + error.message });
        });
    };

    // 提取手机号
    const extractPhoneNumber = (value) => {
      const regex = /^1[3-9]\d{9}/;
      const match = value.match(regex);
      return match ? match[0] : null;
    };

    // 获取令牌
    const getToken = () => {
      if (mainAccount.phoneNumber === mainInfo.phoneNumber) {
        showNotify({
          type: 'warning',
          message: '号码是主号!'
        });
        formKey.value++
        return
      }

      formRef.value.validate(['token']).then(() => {
        formKey.value++
        try {
          const index = additionalAccounts.value.findIndex(i => {
            return i.phone === mainAccount.phoneNumber
          })

          if (index > -1) {
            additionalAccounts.value[index].token = mainAccount.token;
            additionalAccounts.value[index].cid = mainAccount.cid
            showNotify({
              type: 'success',
              message: `小号[${mainAccount.phoneNumber.slice(-4)}]Token更新成功`
            });
          } else {
            // 添加新的小号
            addAccount()
          }
        } catch (error) {
          showNotify({ type: 'danger', message: '更新失败！' });
          console.error('更新失败！:', error);
        }
      }).catch(error => {
        console.warn('表单验证错误:', error);
      })
    };

    // 获取用户信息
    const getUserInfo = () => {
      // 在登录后处理日志轮询
      const cardKey = StorageUtil.getCardKey();
      loginApi.login(cardKey)
        .then(response => {
          mainAccount.phoneNumber = response.phoneNumber;
          mainAccount.expirationTime = response.expirationTime;
          mainAccount.token = response.token;
          mainAccount.cid = response.cid
          mainAccount.allStr = (mainAccount.phoneNumber && mainAccount.token && mainAccount.cid) ? response.phoneNumber + '|' + response.cid + '|' + response.token : ''
          additionalAccounts.value = JSON.parse(response.subTokens) || [];
          // 主号信息
          mainInfo.phoneNumber = response.phoneNumber;
          mainInfo.token = response.token || '';
          mainInfo.cid = response.cid || '';
        })
        .catch(error => {
          console.error('Login failed', error)
        })
    };
    onMounted(() => {
      getUserInfo()
    })

    return {
      // 卡密表单
      cardKeyFormRef,
      cardKeyConfig,
      handleSysConfigSubmit,
      // 表单
      formRef,
      formKey,
      // 主账号信息
      mainAccount,
      mainInfo,
      // 额外账号列表
      additionalAccounts,
      // 新账号手机号
      newAccountPhone,
      newAccountCode,
      // 提交主账号信息方法
      submitMainAccountInfo,
      // 添加账号方法
      addAccount,
      // 删除账号方法
      removeAccount,
      // 获取令牌方法
      getToken,
      // 发送验证码
      sendVerificationCode,
      // 倒计时
      isCounting,
      buttonText,
      countdown,
      // 获取主号 Token
      getTokenCode,
      // 验证令牌格式
      validateToken,
      // 验证手机号码
      validatePhoneNumber
    };
  }
}
</script>

<style lang="less" scoped>
.account {
  padding: 10px;
  background-color: #f5f5f5;

  .van-cell-group {
    position: relative;
    margin: 0 2px;
    margin-bottom: 16px;
    background-color: white;
    border-radius: 12px;
    box-shadow: 0 0 25px rgba(0, 0, 0, 0.08);

    /deep/.van-field__label {
      display: flex;
      align-items: center;
    }
  }

  .account-title {
    font-size: 18px;
    font-weight: 700;
    color: #323233;
    padding-bottom: 0;
  }

  /deep/.account-title.van-cell:after {
    border: none !important;
  }
}

.additional-account {
  margin-bottom: 16px;
}

.add-account-section {
  background-color: #E6EAFA;
  border-radius: 12px;
  padding: 15px;
  margin-top: 16px;

  .add-account-btn {
    background-color: #2051D8;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.form-textarea {
  /deep/ .van-field__body {
    background-color: #FAFAFC;
    border-radius: 5px;
    padding: 5px;
  }
}



// Define color variables for easier management and consistency
@primary-bg-color: #f7f8fa;
@border-color: #ebedf0;
@text-color: #323233;
@sub-text-color: #666;
@shadow-color: rgba(0, 0, 0, 0.05);
@white-color: #ffffff;

.main-account-section,
.sub-accounts-section {
  background-color: @white-color;
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 0 25px @shadow-color;
}

.config-wrapper {
  background-color: @white-color;
  border-radius: 12px;
  margin-bottom: 15px;
  box-shadow: 0 0 25px @shadow-color;

  h3 {
    margin-left: 20px !important;
    margin-top: 13px !important;
  }

  .van-cell-group {
    box-shadow: none;
  }
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: @text-color;
    font-weight: 600;
  }
}

.main-account-form {
  .van-cell-group {
    background-color: transparent;
  }
}

.black-color {
  /deep/.van-field__label {
    color: #333;
  }
}

.token-display {
  margin: 10px auto;
  width: 100%;
}

.token-content {
  width: 100%;
  height: 100px;
  border: 1px solid @border-color;
  border-radius: 8px;
  overflow-y: auto;
  padding: 10px;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 12px;
  line-height: 1.5;
  color: @sub-text-color;
  background-color: @white-color;
}

.additional-account {
  margin-bottom: 15px;
}

.add-account-btn {
  margin-top: 10px;
}
</style>
